#include "daemon_subprocess.h"
#include <stdlib.h>
#include <unistd.h>
#include <log/log.h>

extern char **environ;

SubProcess *daemon_subprocess_init(char *cmd, char *part)
{
    SubProcess *sp = (SubProcess *)malloc(sizeof(SubProcess));
    if (sp == NULL)
    {
        LOGE("malloc SubProcess failed");
        return NULL;
    }
    sp->pid = -1;
    sp->argv = malloc(sizeof(char *) * 3);
    if (sp->argv == NULL)
    {
        LOGE("malloc argv failed");
        free(sp);
        return NULL;
    }
    sp->argv[0] = cmd;
    sp->argv[1] = part;
    sp->argv[2] = NULL;
    sp->envp = environ;

    return sp;
}

int daemon_subprocess_start(SubProcess *sp)
{
    sp->pid = fork();
    if (sp->pid < 0)
    {
        LOGE("fork failed");
        return -1;
    } else if (sp->pid > 0)
    {
        return 0;
    }
    if (execve(sp->argv[0], sp->argv, sp->envp))
    {
        log_fatal("Subprocess start failed");
        exit(EXIT_FAILURE);
    }
    return 0;
}